package light.head.dao.inv;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.DateUtils;
import light.head.model.inv.InvBusinessContacts;
@Service
public class InvBusinessContactsDAO extends BaseDAO<InvBusinessContacts, Serializable>{
	
	
	private final static String sql_findIsc = "FROM InvBusinessContacts ibc WHERE ibc.deleted = 0 AND ibc.isc = ?";
	public RESULT findByMap(List<Integer> ocs, Map<String, String> map, PageBean pb) {
		if (ocs == null ) return null;
		
		StringBuffer hql = new StringBuffer(" FROM InvBusinessContacts ibc WHERE 1=1 AND ibc.oc IN (");
		List<Object> list = new ArrayList<Object>();
		
		for (Integer i : ocs) {
			hql.append("?,");
			list.add(i);
		}
		hql.deleteCharAt(hql.length() - 1).append(")");
		
		if (null != map) {
			String name = map.get(Parm.NAME);
			String isc = map.get("isc");
			String phone = map.get(Parm.PHONE);
			String qq = map.get(Parm.QQ);
			String cu = map.get(Parm.CU);
			String on = map.get(Parm.ON);
			String time1 = map.get(Parm.TIME1);
			String time2 = map.get(Parm.TIME2);
			if (isNotNull(name)) {
				list.add("%" + name + "%");
				hql.append(" AND ibc.name LIKE ?");
			}
			if (isNotNull(isc)) {
				list.add("%" + isc + "%");
				hql.append(" AND ibc.isc LIKE ?");
			}
			if (isNotNull(phone)) {
				list.add("%" + phone + "%");
				hql.append(" AND ibc.phone LIKE ?");
			}
			if (isNotNull(time1)) {
				list.add(DateUtils.getDateByStr(time1, null));
				hql.append(" AND ibc.ct >= ?");
			}
			if (isNotNull(qq)) {
				list.add(Integer.parseInt(qq));
				hql.append(" AND ibc.qq = ?");
			}
			if (isNotNull(cu)) {
				list.add(Integer.parseInt(cu));
				hql.append(" AND ibc.cu = ?");
			}
			if (isNotNull(on)) {
				list.add("%" + on + "%");
				hql.append(" AND ibc.oc IN (SELECT o.code FROM Organ o WHERE o.name LIKE ?)");
			}
			if (isNotNull(time2)) {
				list.add(DateUtils.getDateByStr(time2, null));
				hql.append(" AND ibc.ct >= ?");
			}
		}
		hql.append(" ORDER BY ibc.code DESC");
		return findToPageBean(hql.toString(), pb, list);
	}
	
	/**
	 * 通过单位编号获取联系人
	 * @param isc		业务编号
	 */
	public List<InvBusinessContacts> findIsc(Integer isc) {
		if (null == isc) return null;
		return find(sql_findIsc, null, null, isc);
	}
}
